package com.fm.demo.utils

import android.view.View

/**
 *
 * 扩展点击事件
 * 防止连续点击
 *
 * */

private var tagIntervalMillis = 1234561123
private var tagClickLastTime = 1234561124
private var defaultIntervalMillis = 600L

/**
 * 点击事件的View扩展
 * @param block: (T) -> Unit 函数
 * @return Unit
 */
inline fun <reified T : View> T.click(crossinline block: (T) -> Unit) = setOnClickListener {
    block(it as T)
}

/**
 * 设置延迟时间的View扩展
 * @param interval Long 延迟时间，默认600毫秒
 * @return T
 */
fun <T : View> T.clickWithInterval(interval: Long = defaultIntervalMillis): T {
    triggerInterval = interval
    return this
}

/**
 * 带延迟过滤的点击事件View扩展
 * @param interval Long 延迟时间，默认600毫秒
 * @param block: (T) -> Unit 函数
 * @return Unit
 */
internal inline fun <reified T : View> T.clickWithInterval(interval: Long = defaultIntervalMillis, crossinline block: (T) -> Unit) {
    this.triggerInterval = interval
    setOnClickListener {
        if (clickEnable()) {
            block(it as T)
        }
    }
}

private var <T : View> T.triggerLastTime: Long
    get() = if (getTag(tagClickLastTime) != null) {
        getTag(tagClickLastTime) as Long
    } else {
        -(defaultIntervalMillis + 1)
    }
    set(value) {
        setTag(tagClickLastTime, value)
    }

private var <T : View> T.triggerInterval: Long
    get() = if (getTag(tagIntervalMillis) != null) {
        getTag(tagIntervalMillis) as Long
    } else {
        defaultIntervalMillis
    }
    set(value) {
        setTag(tagIntervalMillis, value)
    }

private fun <T : View> T.clickEnable(): Boolean {
    var flag = false
    val currentClickTime = System.currentTimeMillis()
    if (currentClickTime - triggerLastTime >= triggerInterval) {
        flag = true
        triggerLastTime = currentClickTime
    }
    return flag
}

/**
 * 带延迟过滤的点击事件监听，见[View.OnClickListener]
 * 延迟时间根据triggerDelay获取：600毫秒，不能动态设置
 */
interface OnLazyClickListener : View.OnClickListener {

    override fun onClick(v: View?) {
        if (v?.clickEnable() == true) {
            onLazyClick(v)
        }
    }

    fun onLazyClick(v: View)
}